//
//  UIView+YY.m
//  YiYunSTP
//
//  Created by apple on 2019/3/21.
//  Copyright © 2019年 yiyuniot. All rights reserved.
//
#pragma mark --<Base>
#import "UIView+YY.h"
#import "SHCommonDefines.h"
#import <objc/runtime.h>

@implementation UIView (YY)

- (CGFloat)x
{
    return self.frame.origin.x;
}

- (void)setX:(CGFloat)x
{
    CGRect frame = self.frame;
    frame.origin.x = x;
    self.frame = frame;
}

- (CGFloat)y
{
    return self.frame.origin.y;
}

- (void)setY:(CGFloat)y
{
    CGRect frame = self.frame;
    frame.origin.y = y;
    self.frame = frame;
}

- (CGFloat)maxX
{
    return self.frame.origin.x + self.frame.size.width;
}

- (void)setMaxX:(CGFloat)maxX
{
    CGRect frame = self.frame;
    frame.origin.x = maxX - frame.size.width;
    self.frame = frame;
}


- (CGFloat)maxY
{
    return CGRectGetMaxY(self.frame);
}

- (void)setMaxY:(CGFloat)maxY
{
    CGRect frame = self.frame;
    frame.origin.y = maxY - frame.size.height;
    self.frame = frame;
}

- (CGFloat)centerX
{
    return self.center.x;
}

- (void)setCenterX:(CGFloat)centerX
{
    self.center = CGPointMake(centerX, self.center.y);
}

- (CGFloat)centerY
{
    return self.center.y;
}

- (void)setCenterY:(CGFloat)centerY
{
    self.center = CGPointMake(self.center.x, centerY);
}

- (CGFloat)width
{
    return self.frame.size.width;
}

- (void)setWidth:(CGFloat)width
{
    CGRect frame = self.frame;
    frame.size.width = width;
    self.frame = frame;
}

- (CGFloat)height
{
    return self.frame.size.height;
}

- (void)setHeight:(CGFloat)height
{
    CGRect frame = self.frame;
    frame.size.height = height;
    self.frame = frame;
}

- (CGPoint)origin
{
    return self.frame.origin;
}

- (void)setOrigin:(CGPoint)origin
{
    CGRect frame = self.frame;
    frame.origin = origin;
    self.frame = frame;
}

- (CGSize)size {
    return self.frame.size;
}


- (void)setSize:(CGSize)size
{
    CGRect frame = self.frame;
    frame.size = size;
    self.frame = frame;
}

@end
#pragma mark --<Shadow>
#import <objc/runtime.h>
@implementation UIView (Shadow)

-(void)setYy_ShadowRadius:(CGFloat)yy_ShadowRadius{
    objc_setAssociatedObject(self, "yy_ShadowRadius", [NSNumber numberWithFloat:yy_ShadowRadius], OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self yy_DrawShadowWithRadius:yy_ShadowRadius];
}

-(CGFloat)yy_ShadowRadius{
    return [objc_getAssociatedObject(self, "shadowRadius") floatValue];
}

-(void)setYy_ShadowColor:(UIColor *)yy_ShadowColor{
    objc_setAssociatedObject(self, "yy_ShadowColor", yy_ShadowColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

-(UIColor *)yy_ShadowColor{
    return objc_getAssociatedObject(self, "yy_ShadowColor");
}



-(void)yy_DrawShadowWithRadius:(CGFloat)radius{
    if (self.yy_ShadowColor == nil) {
        self.yy_ShadowColor = [UIColor grayColor];
    }
    self.layer.cornerRadius = radius;
    self.layer.shadowColor = self.yy_ShadowColor.CGColor;
    self.layer.shadowOpacity = 1;
    self.layer.shadowOffset = CGSizeMake(0, 0);
    self.layer.shadowRadius = 3.0f;
    UIBezierPath *btnShadowPath = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:radius];
    self.layer.shadowPath = btnShadowPath.CGPath;
}

-(void)yy_drawCornerRadius:(CGFloat)cornerRadius borderColor:(UIColor *)borderColor{
    if (borderColor == nil) {
        borderColor = UIColor.clearColor;
    }
    for (CALayer *layer in self.layer.sublayers) {
        if ([layer isKindOfClass:[CAShapeLayer class]]) {
            [layer removeFromSuperlayer];
        }
    }
    CAShapeLayer *maskLayer = [CAShapeLayer layer];
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds cornerRadius:cornerRadius];
    maskLayer.path = path.CGPath;
    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.lineWidth = 1.0f;
    borderLayer.strokeColor = borderColor.CGColor;
    borderLayer.fillColor = [UIColor clearColor].CGColor;
    borderLayer.path = path.CGPath;
    [self.layer addSublayer:borderLayer];
    [self.layer setMask:maskLayer];
}

- (void)yy_drawCornerRadius:(CGFloat)cornerRadius borderColor:(UIColor *)borderColor byRoundingCorners:(UIRectCorner)corners {
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(cornerRadius, cornerRadius)];
    CAShapeLayer *shapLayer = [[CAShapeLayer alloc] init];
    shapLayer.lineWidth = 1.0f;
    shapLayer.strokeColor = borderColor.CGColor;
    shapLayer.fillColor = UIColor.clearColor.CGColor;
    shapLayer.frame = self.bounds;
    shapLayer.path = path.CGPath;
    [self.layer insertSublayer:shapLayer atIndex:0];
}

- (void)yy_addCornerRadius:(CGFloat)radius borderWidth:(CGFloat)borderWidth backgroundColor:(UIColor*)backgroundColor borderColor:(UIColor *)borderColor {
    CGSize size = self.bounds.size;
    UIGraphicsBeginImageContextWithOptions(size, NO, [UIScreen mainScreen].scale);
    CGContextRef contextRef =  UIGraphicsGetCurrentContext();
    
    CGContextSetLineWidth(contextRef, borderWidth);
    CGContextSetStrokeColorWithColor(contextRef, borderColor.CGColor);
    CGContextSetFillColorWithColor(contextRef, backgroundColor.CGColor);
    
    CGFloat halfBorderWidth = borderWidth / 2.0;
    CGFloat width = size.width;
    CGFloat height = size.height;
    
    CGContextMoveToPoint(contextRef, width - halfBorderWidth, radius + halfBorderWidth);
    CGContextAddArcToPoint(contextRef, width - halfBorderWidth, height - halfBorderWidth, width - radius - halfBorderWidth, height - halfBorderWidth, radius);  // 右下角角度
    CGContextAddArcToPoint(contextRef, halfBorderWidth, height - halfBorderWidth, halfBorderWidth, height - radius - halfBorderWidth, radius); // 左下角角度
    CGContextAddArcToPoint(contextRef, halfBorderWidth, halfBorderWidth, width - halfBorderWidth, halfBorderWidth, radius); // 左上角
    CGContextAddArcToPoint(contextRef, width - halfBorderWidth, halfBorderWidth, width - halfBorderWidth, radius + halfBorderWidth, radius); // 右上角
    CGContextDrawPath(contextRef, kCGPathFillStroke);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
    [self insertSubview:imageView atIndex:0];
}

#pragma mark  Dash
- (void)yy_drawDashLineColor:(UIColor *)lineColor lineDashPattern:(NSArray<NSNumber *> *)lineDashPattern lineRect:(CGRect)lineRect isHorizonal:(BOOL)isHorizonal
{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:self.bounds];
    [shapeLayer setPosition:CGPointMake(CGRectGetWidth(self.frame) / 2, CGRectGetHeight(self.frame)/2)];
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //设置虚线颜色
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //设置虚线宽度
    [shapeLayer setLineWidth:1.0];
    [shapeLayer setLineJoin:kCALineJoinRound];
    [shapeLayer setLineCap:kCALineCapButt];
    //设置虚线样式
    [shapeLayer setLineDashPattern:lineDashPattern];
    //设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, CGRectGetMinX(lineRect), CGRectGetMinY(lineRect));
    if (isHorizonal) {//水平线
        CGPathAddLineToPoint(path, NULL, CGRectGetMaxX(lineRect), CGRectGetMinY(lineRect));
    }
    else {//竖直线
        CGPathAddLineToPoint(path, NULL, CGRectGetMinX(lineRect), CGRectGetMaxY(lineRect));
    }
    [shapeLayer setPath:path];
    CGPathRelease(path);
    
    //把绘制好的虚线添加上来
    [self.layer addSublayer:shapeLayer];
}


- (void)yy_drawCornerRadius:(CGFloat)radius byRoundingCorners:(UIRectCorner)corners {
    UIBezierPath *path = [UIBezierPath bezierPathWithRoundedRect:self.bounds byRoundingCorners:corners cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *shapLayer = [[CAShapeLayer alloc] init];
    shapLayer.frame = self.bounds;
    shapLayer.path = path.CGPath;
    self.layer.mask = shapLayer;
}

@end

@implementation UIView (Present)
/** 找到自己的vc */
- (UIViewController *)viewController{
    for (UIView* next = self; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]]) {
            return (UIViewController*)nextResponder;
        }
    }
    return nil;
}

-(void)removeAllSubViews{
    for (UIView *view in self.subviews) {
        [view removeFromSuperview];
    }
}
@end

@implementation UIView (Border)

- (CAShapeLayer *)yy_borderLayer {
    return objc_getAssociatedObject(self, _cmd);
}

- (void)setYy_borderLayer:(CAShapeLayer * _Nullable)yy_borderLayer {
    objc_setAssociatedObject(self, @selector(yy_borderLayer), yy_borderLayer, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}

+ (void)load {
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        Class class = [self class];
        SEL originalSelector = @selector(layoutSublayersOfLayer:);
        SEL swizzledSelector = @selector(yy_layoutSublayersOfLayer:);
        ReplaceMethod(class, originalSelector, swizzledSelector);
    });
}

- (void)yy_layoutSublayersOfLayer:(CALayer *)layer {
    [self yy_layoutSublayersOfLayer:layer];
    
    if ((!self.yy_borderLayer && self.yy_borderPosition == QMUIViewBorderPositionNone) || (!self.yy_borderLayer && self.yy_borderWidth == 0)) {
        return;
    }
    
    if (self.yy_borderLayer && self.yy_borderPosition == QMUIViewBorderPositionNone && !self.yy_borderLayer.path) {
        return;
    }
    
    if (self.yy_borderLayer && self.yy_borderWidth == 0 && self.yy_borderLayer.lineWidth == 0) {
        return;
    }
    
    if (!self.yy_borderLayer) {
        self.yy_borderLayer = [CAShapeLayer layer];
        self.yy_borderLayer.fillColor = UIColor.clearColor.CGColor;
//        [self.yy_borderLayer qmui_removeDefaultAnimations];
        [self.layer addSublayer:self.yy_borderLayer];
    }
    self.yy_borderLayer.frame = self.bounds;
    
    CGFloat borderWidth = self.yy_borderWidth;
    self.yy_borderLayer.lineWidth = borderWidth;
    self.yy_borderLayer.strokeColor = self.yy_borderColor.CGColor;
    
    UIBezierPath *path = nil;
    
    if (self.yy_borderPosition != QMUIViewBorderPositionNone) {
        path = [UIBezierPath bezierPath];
    }
    
    CGFloat (^adjustsLocation)(CGFloat, CGFloat, CGFloat) = ^CGFloat(CGFloat inside, CGFloat center, CGFloat outside) {
//        self.qmui_borderLocation == QMUIViewBorderLocationInside ? inside : (self.qmui_borderLocation == QMUIViewBorderLocationCenter ? center : outside);
        return inside;
    };
    
    CGFloat lineOffset = adjustsLocation(borderWidth / 2.0, 0, -borderWidth / 2.0); // 为了像素对齐而做的偏移
    CGFloat lineCapOffset = adjustsLocation(0, borderWidth / 2.0, borderWidth); // 两条相邻的边框连接的位置
    
    BOOL shouldShowTopBorder = (self.yy_borderPosition & QMUIViewBorderPositionTop) == QMUIViewBorderPositionTop;
    BOOL shouldShowLeftBorder = (self.yy_borderPosition & QMUIViewBorderPositionLeft) == QMUIViewBorderPositionLeft;
    BOOL shouldShowBottomBorder = (self.yy_borderPosition & QMUIViewBorderPositionBottom) == QMUIViewBorderPositionBottom;
    BOOL shouldShowRightBorder = (self.yy_borderPosition & QMUIViewBorderPositionRight) == QMUIViewBorderPositionRight;
    
    UIBezierPath *topPath = [UIBezierPath bezierPath];
    UIBezierPath *leftPath = [UIBezierPath bezierPath];
    UIBezierPath *bottomPath = [UIBezierPath bezierPath];
    UIBezierPath *rightPath = [UIBezierPath bezierPath];
    
    [topPath moveToPoint:CGPointMake(shouldShowLeftBorder ? -lineCapOffset : 0, lineOffset)];
    [topPath addLineToPoint:CGPointMake(CGRectGetWidth(self.bounds) + (shouldShowRightBorder ? lineCapOffset : 0), lineOffset)];
    
    [leftPath moveToPoint:CGPointMake(lineOffset, shouldShowTopBorder ? -lineCapOffset : 0)];
    [leftPath addLineToPoint:CGPointMake(lineOffset, CGRectGetHeight(self.bounds) + (shouldShowBottomBorder ? lineCapOffset : 0))];
    
    CGFloat y = CGRectGetHeight(self.bounds) - lineOffset;
    [bottomPath moveToPoint:CGPointMake(shouldShowLeftBorder ? -lineCapOffset : 0, y)];
    [bottomPath addLineToPoint:CGPointMake(CGRectGetWidth(self.bounds) + (shouldShowRightBorder ? lineCapOffset : 0), y)];
    
    CGFloat x = CGRectGetWidth(self.bounds) - lineOffset;
    [rightPath moveToPoint:CGPointMake(x, CGRectGetHeight(self.bounds) + (shouldShowBottomBorder ? lineCapOffset : 0))];
    [rightPath addLineToPoint:CGPointMake(x, shouldShowTopBorder ? -lineCapOffset : 0)];
    
    if (shouldShowTopBorder && ![topPath isEmpty]) {
        [path appendPath:topPath];
    }
    if (shouldShowLeftBorder && ![leftPath isEmpty]) {
        [path appendPath:leftPath];
    }
    if (shouldShowBottomBorder && ![bottomPath isEmpty]) {
        [path appendPath:bottomPath];
    }
    if (shouldShowRightBorder && ![rightPath isEmpty]) {
        [path appendPath:rightPath];
    }
    
    self.yy_borderLayer.path = path.CGPath;
}

// 关联属性
- (UIColor *)yy_borderColor {
    return (UIColor *)objc_getAssociatedObject(self, _cmd);
}

- (void)setYy_borderColor:(UIColor *)yy_borderColor {
    objc_setAssociatedObject(self, @selector(yy_borderColor), yy_borderColor, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setNeedsLayout];
}

- (CGFloat)yy_borderWidth {
    return [(NSNumber *)objc_getAssociatedObject(self, _cmd) floatValue];
}

- (void)setYy_borderWidth:(CGFloat)yy_borderWidth {
    objc_setAssociatedObject(self, @selector(yy_borderWidth), @(yy_borderWidth), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setNeedsLayout];
}

- (QMUIViewBorderPosition)yy_borderPosition {
    return (QMUIViewBorderPosition)[objc_getAssociatedObject(self, _cmd) unsignedIntegerValue];
}

- (void)setYy_borderPosition:(QMUIViewBorderPosition)yy_borderPosition {
    objc_setAssociatedObject(self, @selector(yy_borderPosition), @(yy_borderPosition), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
    [self setNeedsLayout];
}

@end

